package com.fauks.se.jdk8.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * <pre>
 *     author : slx
 *     time   : 2020/04/13
 *     desc   :
 * </pre>
 */
public class StreamTest {
    public static void main(String[] args) {
        //createStream();
        //filterStream();
        //mapStream();
        //reduceStream();
        collcetionStream();
    }

    //收集
    private static void collcetionStream() {
        //将年龄大于20的添加到集合中
        List<Student> students = StudentData.getStudents().stream()
                .filter(item -> item.getAge() > 20)
                .collect(Collectors.toList());
        students.forEach(System.out::println);
    }

    //归约
    private static void reduceStream() {
        //计算总分
        Optional<Double> reduce = StudentData.getStudents().stream()
                .map(Student::getScore)
                .reduce(Double::sum);
        System.out.println(reduce.orElse(0.0));
    }

    //映射
    private static void mapStream() {
        //将流中元素转换为age(int)，再筛选
        StudentData.getStudents().stream().map(Student::getAge).filter(age -> age > 20)
                .forEach(System.out::println);
    }

    //筛选、切片
    private static void filterStream() {
        Stream<Student> stream = StudentData.getStudents().stream();
        //筛选出年龄大于20的
        //stream.filter(item -> item.getAge() > 20).forEach(System.out::println);

        //截断，去除前3条数据
        //stream.limit(3).forEach(System.out::println);

        //去重
        //stream.distinct().forEach(System.out::println);

        //跳过前5条元素
        stream.skip(5).forEach(System.out::println);
    }

    //创建Steam
    private static void createStream() {
        List<Student> students = StudentData.getStudents();
        //顺序流
        Stream<Student> stream = students.stream();
        //并行流
        Stream<Student> studentStream = students.parallelStream();

        //通过数组创建
        int[] array = {1, 2, 3};
        IntStream arrayStream = Arrays.stream(array);

        //通过Stream.of
        Stream<Integer> integerStream = Stream.of(1, 2);

        //创建无限流
        //循环5次
        Stream.iterate(0, t -> t + 5).limit(5).forEach(System.out::println);
    }
}
